package com.FH.organization.email_contact;

import com.FH.organization.Attachment.AttachmentResource;
import com.FH.util.AccessDB;
import com.FH.util.FileProcess;
import com.FH.util.ResultDTO;
import com.FH.util.warnSrc;
import org.codehaus.jettison.json.JSONObject;

import javax.ejb.Stateless;
import javax.inject.Inject;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by Administrator on 2016/12/12.
 */
@Stateless
public class emialContactDAOImp extends AccessDB implements emailContactDAO {
    @Inject
    email_contactResoure email_contactResoure;
    @Inject
    AttachmentResource attachmentResource;

    @Override
    public ResultDTO getemailContactInfo(String search, String page, String size) {

        ResultDTO resultDTO = new ResultDTO();
        try {
            JSONObject json = new JSONObject(search);
            String existName = "0";

            String sqlexit = "select count(1) from email_contact where 1=1 ";

            String sql_w = "";//查询条件sql组合

            String sql_page = "";//分页sql组合
            Integer page_ok = Integer.parseInt(page);
            Integer size_ok = Integer.parseInt(size);
            if (page.equals("1")) {
                sql_page = " limit 0," + size + "";
            } else {
                sql_page = " limit " + ((page_ok - 1) * size_ok + 1) + "," + size + "";
            }

            if (json.has("contact_id")) {
                sql_w += " AND contact_id ='" + json.getString("contact_id") + "'";
            }
            if (json.has("contact_groupid")) {
                sql_w += " AND contact_groupid ='" + json.getString("contact_groupid") + "'";
            }


            String sql_ok = sqlexit + sql_w;//组合好的sql语句
            existName = getReportingToOne(sql_ok);//查询此数据是否存在

            List<String[]> seresult = new ArrayList<String[]>();

            List<email_contactShowDTO> result = new ArrayList<email_contactShowDTO>();

            if (!existName.equals("0")) {
                String sql = "select contact_id,contact_name,email,contact_phone,company,address,attachment_id from email_contact where 1=1" + sql_w + sql_page;
                seresult = this.getReportingTo(sql);

                for (int i = 0; i < seresult.size(); i++) {

                    email_contactShowDTO sysmenuShowDTO = new email_contactShowDTO();
                    sysmenuShowDTO.setContact_id(seresult.get(i)[1]);
                    sysmenuShowDTO.setContact_name(seresult.get(i)[2]);
                    sysmenuShowDTO.setEmail(seresult.get(i)[3]);
                    sysmenuShowDTO.setContact_phone(seresult.get(i)[4]);
                    sysmenuShowDTO.setCompany(seresult.get(i)[5]);
                    sysmenuShowDTO.setAddress(seresult.get(i)[6]);
                    sysmenuShowDTO.setAttachment_id(seresult.get(i)[7]);
                    ResultDTO attach = null;
                    if (seresult.get(i)[7] != null && !seresult.get(i)[7].equals("")) {
                        attach = attachmentResource.getAttachmentInfo("{attachment_id:" + seresult.get(i)[7] + "}", "1", "1");
                        sysmenuShowDTO.setImages(attach.getValues());
                    }

                    result.add(sysmenuShowDTO);
                }

            }

            if (seresult.size() != 0) {
                resultDTO.setValues(result);
                resultDTO.setStatus("90000");
                resultDTO.setDescritpion(warnSrc.get_success);
            } else {
                resultDTO.setStatus("90001");
                resultDTO.setDescritpion(warnSrc.get_fail);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultDTO;
    }

    @Override
    public ResultDTO addemailContactInfo(email_contactPullDTO dataDTO) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(new Date());

        int resultls = 0;

        String existName = "";
        /**
         * 判断合同申请单中是否已存在此数据
         *
         * 若存在  进行更新
         *
         * 如不存在 执行add方法
         *
         */
        String contact_id = dataDTO.getContact_id();
        if (contact_id != null && !contact_id.equals("")) {

            String sql = "select count(1) from email_contact where contact_id='" + dataDTO.getContact_id() + "'";

            existName = getReportingToOne(sql);

            if (!existName.equals("0")) {
                return email_contactResoure.updateemailContactInfo(dataDTO);
            }
        }

        //构建返回对象
        ResultDTO resultDTO = new ResultDTO();
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
        // if(existCarmanage.equals("0")){
        String attach_id = "";
        if (null != dataDTO.getFilestream() && !"".equals(dataDTO.getFilestream())) {
            attach_id = getImage(dataDTO);
        }


        String contract_insert = "";
        contract_insert += "insert into email_contact(contact_id,contact_name,email,contact_phone,company,address,attachment_id,create_time,contact_groupid) " +
                "values ('" + uuid + "','" + dataDTO.getContact_name() + "','" + dataDTO.getEmail() + "','" + dataDTO.getContact_phone() + "'" +
                ",'" + dataDTO.getCompany() + "','" + dataDTO.getAddress() + "','" + attach_id + "','" + time + "','" + dataDTO.getContact_groupid() + "')";
        //插入业务表
        resultls = addReportingTo(contract_insert);
        if (resultls != 0) {
            resultDTO.setStr(uuid);
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.add_success);
        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.add_fail);
        }

        return resultDTO;
    }

    @Override
    public ResultDTO deleteemailContactInfo(email_contactPullDTO dataDTO) {
        String sql = "select count(1) from email_contact where contact_id='" + dataDTO.getContact_id() + "'";

        String existName = getReportingToOne(sql);

        int result = 0;

        ResultDTO resultDTO = new ResultDTO();

        if (!existName.equals("0")) {

            String QUERY = "delete from email_contact where contact_id='" + dataDTO.getContact_id() + "'";

            result = this.addReportingTo(QUERY);
        }

        if (result != 0) {
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.delete_success);
        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.delete_fail);
        }
        return resultDTO;
    }

    @Override
    public ResultDTO updateemailContactInfo(email_contactPullDTO dataDTO) {
        String member_id = "select count(1) from email_contact WHERE contact_id='" + dataDTO.getContact_id() + "'";

        String existName = getReportingToOne(member_id);

        int resultls = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(new Date());

        //构建返回对象
        ResultDTO resultDTO = new ResultDTO();
        if (!existName.equals("0")) {
            String QUERY = "";
            QUERY += "update email_contact set create_time='" + time + "'";
            if (null != dataDTO.getContact_name() && !"".equals(dataDTO.getContact_name())) {
                QUERY += ",contact_name='" + dataDTO.getContact_name() + "'";
            }
            if (null != dataDTO.getEmail() && !"".equals(dataDTO.getEmail())) {
                QUERY += ",email='" + dataDTO.getEmail() + "'";
            }
            if (null != dataDTO.getContact_phone() && !"".equals(dataDTO.getContact_phone())) {
                QUERY += ",contact_phone='" + dataDTO.getContact_phone() + "'";
            }
            if (null != dataDTO.getCompany() && !"".equals(dataDTO.getCompany())) {
                QUERY += ",company='" + dataDTO.getCompany() + "'";
            }
            if (null != dataDTO.getAddress() && !"".equals(dataDTO.getAddress())) {
                QUERY += ",address='" + dataDTO.getAddress() + "'";
            }


            if (null != dataDTO.getAttachment_id() && !"".equals(dataDTO.getAttachment_id()) && null != dataDTO.getFilestream() && !"".equals(dataDTO.getFilestream())) {
                //调用修改文件方法
                updateImage(dataDTO);
            } else if (null != dataDTO.getFilestream() && !"".equals(dataDTO.getFilestream())) {
                String uid = getImage(dataDTO);
                QUERY += ",attachment_id='" + uid + "'";

            }
            QUERY += " where contact_id='" + dataDTO.getContact_id() + "'";

            resultls = addReportingTo(QUERY);
        }

        if (resultls != 0) {
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.update_success);

        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.update_fail);
        }

        return resultDTO;

    }

    public String getImage(email_contactPullDTO dataDTO) {
        ResultDTO resultDTO = new ResultDTO();
        // TODO Auto-generated method stub
        String enpenform_image = "";
        //获取配置图片地址
        String[] image_path = this.getImage_path();
        String image_pathAddr = image_path[1];//服务器项目目录地址
        String image_pathSerAddr = image_path[2];//图片访问地址
        String imgDirct = image_pathAddr + "/menu";
        File f = new File(imgDirct);
        if (!f.exists()) {
            f.mkdirs();
            f.setWritable(true, false);
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");

        String imgPath = imgDirct + "/" + uuid + ".png";


        //base64字符串保存为图片
        boolean headImg = FileProcess.GenerateImage(dataDTO.getFilestream(), imgPath);
        FileProcess.newlog("执行头像图片储存方法，储存照片地址：" + imgPath + " 方法返回：" + headImg);
        int resultls = 0;
        int mresult = 0;

        String imgurl = "/menu/" + uuid + ".png";

        //ArrayList<HeadPortaitDTO> result = new ArrayList<HeadPortaitDTO>();

        if (headImg) {
            //插入头像表
            enpenform_image += "insert into attachment(attachment_id,attachment_addr,head_portrait_time,file_type,file_name) values ('" + uuid + "','" + imgurl + "','" + df.format(new Date()) + "','" + uuid + ".png" + "','" + uuid + ".png" + "')";
            // enpenform_image += "insert into file(file_id,file_addr,file_time,filegui_id,file_name) values ('" + uuid + "','" +imgurl+ "','" +df.format(new Date()) + "','" + dataDTO.getFilegui_id() + "','" + dataDTO.getFiletype() + "')";
            //执行sql
            resultls = addReportingTo(enpenform_image);
        }

        if (resultls != 0) {
            return uuid;
        }
        return null;
    }

    public String updateImage(email_contactPullDTO dataDTO) {
        // TODO Auto-generated method stub
        String enpenform_image = "";
        //获取配置图片地址
        String[] image_path = this.getImage_path();
        String image_pathAddr = image_path[1];//服务器项目目录地址
        String image_pathSerAddr = image_path[2];//图片访问地址
        String imgDirct = image_pathAddr + "/menu";
        File f = new File(imgDirct);
        if (!f.exists()) {
            f.mkdirs();
            f.setWritable(true, false);
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");

        String imgPath = imgDirct + "/" + uuid + ".png";

        //base64字符串保存为图片
        boolean headImg = FileProcess.GenerateImage(dataDTO.getFilestream(), imgPath);
        FileProcess.newlog("执行头像图片储存方法，储存照片地址：" + imgPath + " 方法返回：" + headImg);
        int resultls = 0;
        int mresult = 0;

        String imgurl = "/menu/" + uuid + ".png";

        //ArrayList<HeadPortaitDTO> result = new ArrayList<HeadPortaitDTO>();

        if (headImg) {
            //修改头像表
            enpenform_image += "update attachment set attachment_addr='" + imgurl + "',head_portrait_time = '" + df.format(new Date()) + "',file_type = '" + uuid + ".png" + "',file_name = '" + uuid + ".png" + "' where attachment_id='" + dataDTO.getAttachment_id() + "'";
            // enpenform_image += "insert into attachment(attachment_id,attachment_addr,head_portrait_time) values ('" + uuid + "','" + imgurl + "','" + df.format(new Date()) + "')";
            //执行sql
            resultls = addReportingTo(enpenform_image);
        }


        if (resultls != 0) {
            return uuid;
        }
        return null;
    }
}
